package com.nine.mymall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.nine.common.constant.AuthServerConstant;
import com.nine.common.exception.BizCodeEnum;
import com.nine.common.utils.R;
import com.nine.mymall.auth.feign.MemberFeignService;
import com.nine.mymall.auth.feign.ThirdPartFeignService;
import com.nine.mymall.auth.vo.UserLoginVo;
import com.nine.mymall.auth.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: duonine
 * @date: 2021/12/7
 */
@Slf4j
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {

        // TODO 1、接口防刷

        String codeKey = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String redisCode = redisTemplate.opsForValue().get(codeKey);
        if (StringUtils.isNotBlank(redisCode)) {
            Long time = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - time < 60 * 1000) {
                // 60s内不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        String mycode = code + "_" + System.currentTimeMillis();

        // 2、验证码的再次校验（redis）key-phone,value-code，sms:code:151****---->112233
        // redis缓存验证码，防止同一个手机号再次发送
        redisTemplate.opsForValue().set(codeKey, mycode, 10, TimeUnit.MINUTES);

        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * TODO 重定向传递数据，利用session原理，将数据放到session中，只要跳到下一个页面取出这数据之后，session里面的数据就会删掉
     * TODO 分布式下的session问题
     *
     * @param vo
     * @param result
     * @param redirectAttributes 重定向传递数据
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes) {

        // 校验出错，转到注册页
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> fieldError.getField(), FieldError::getDefaultMessage));
            // System.out.println("errors==="+errors);
            redirectAttributes.addFlashAttribute("errors", errors);

            // Request method 'POST' not supported
            // 用户注册---->/regist(post请求)--------->转发reg.html（路径映射默认都是get请求访问），但是该请求是post请求，请求原封不动转发会出现此报错，因此改为直接渲染
            // return "forward:/reg.html";
            return "redirect:http://auth.mymall.com/reg.html";
        }

        String code = vo.getCode();

        String redis_code = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.isNotBlank(redis_code)) {
            //验证码通过
            if (code.equals(redis_code.split("_")[0])) {
                // 删除验证码；令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());

                // 实现注册功能，远程调用member模块
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    // 成功
                    // 注册成功，跳转到登录页
                    return "redirect:http://auth.mymall.com/login.html";
                } else {
                    //    失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.mymall.com/reg.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误！");
                redirectAttributes.addFlashAttribute("errors", errors);
                // 检验出错、转发到注册页
                return "redirect:http://auth.mymall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误！");
            redirectAttributes.addFlashAttribute("errors", errors);
            // 检验出错、转发到注册页
            return "redirect:http://auth.mymall.com/reg.html";
        }
    }

    /**
     * 页面提交的数据是 k-v 形式，不是json格式，因此不需要写 requestBosy
     *
     * @param vo
     * @return
     * @RequestBody主要用来接收前端传递给后端的json字符串中的数据
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes) {

        // 远程调用登录请求

        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            //    成功
            log.info("{}，欢迎登录成功。。。。。。。。。", vo.getLoginaccount());
            return "redirect:http://mymall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mymall.com/login.html";
        }


    }


}
